#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QFile>
#include <QDir>
#include <QMessageBox>
#include <QEventLoop>

#include "httpdownload.h"

HttpDownload::HttpDownload(QObject *parent) :
    QObject(parent),m_manager(new QNetworkAccessManager(this))
{
}

void HttpDownload::replyNewDate(){
    if(m_file){
        m_file->write(m_reply->readAll());
        m_file->flush();
    }
}

void HttpDownload::replyFinished(){
    // 能通过reply读取请求的所有数据大小和吗？貌似很难，这种流式数据
    m_reply->deleteLater();
    m_file->close();
    m_file->deleteLater();
    emit finished(m_down_size);
}

void HttpDownload::replyError(){
    m_down_size = 0;
    emit finished(m_down_size);
}

void HttpDownload::replyProgress(qint64 recv,qint64 total)
{
    m_down_size = total;//当数据大时，这会被重复设置
}

void HttpDownload::setParam(const QString &url,const QString &file,const QString &dir)
{
    m_url = url;
    m_fileName = file;
    m_dir = dir;
}

void HttpDownload::launch()
{
    downloadFile();
}

void HttpDownload::downloadFile(){
    m_reply = m_manager->get(QNetworkRequest(QUrl(m_url)));
    if(m_dir.isEmpty()){
        m_file = new QFile(m_fileName);
    }else{
        QDir directory(m_dir);
        if(!directory.exists()){
            directory.mkpath(m_dir);
        }
        if(m_dir.endsWith("/"))
            m_file = new QFile(m_dir + m_fileName);
        else
            m_file = new QFile(m_dir + "/" + m_fileName);
    }

    if(!m_file->open(QIODevice::WriteOnly)){
        qDebug() << "error file open failed";
        return;
    }
    connect(m_reply,SIGNAL(readyRead()),this,SLOT(replyNewDate()));

    connect(m_reply,SIGNAL(finished()),this,SLOT(replyFinished()));

    connect(m_reply,SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(replyError()));

    connect(m_reply,SIGNAL(downloadProgress(qint64,qint64)),this,SLOT(replyProgress(qint64,qint64)));
}

